package 设计模式.享元模式;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @description:
 * @author: Kk
 * @create: 2020-12-09 10:24
 **/
public class Flyweight {
    public static void main(String[] args) {

        TreeNode treeNode1=new TreeNode(3,4,TreeFactory.getTree("tree1","data1"));
        TreeNode treeNode2=new TreeNode(5,4,TreeFactory.getTree("tree1","data2"));
    }
}

class TreeNode{
    private int x;
    private int y;
    private Tree tree;

    public TreeNode(int x, int y, Tree tree) {
        this.x = x;
        this.y = y;
        this.tree = tree;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public Tree getTree() {
        return tree;
    }

    public void setTree(Tree tree) {
        this.tree = tree;
    }
}

class Tree{
    private final String name;
    private final String data;

    public Tree(String name, String data) {
        this.name = name;
        this.data = data;
    }

    public String getName() {
        return name;
    }

    public String getData() {
        return data;
    }
}

class TreeFactory{
    //用来产生树
    private static Map<String ,Tree> map=new ConcurrentHashMap<>();
    public static Tree getTree(String name,String data){
        if (map.containsKey(name)){
            return map.get(name);
        }
        Tree tree=new Tree(name,data);
        map.put(name,tree);
        System.out.println(name+"树已经创建");
        return tree;
    }

}
